export type Mode = 'transparent' | 'light'

export const MODE_DEFAULT: Mode = 'transparent'

export function useHeader(initialMode: Mode = MODE_DEFAULT) {
  const router = useRouter()
  router.afterEach(() => {
    resetMode()
  })

  const store = useGlobalStore()
  // NOTE: state 直接解构会失去响应式
  const { headerMode, searchVisible, pendingHeaderMode } = storeToRefs(store)
  // NOTE: getter 可以直接解构
  const { changeHeaderMode, toggleSearchVisible, changeSearchVisible, restoreNextMode } = (store)

  function resetMode() {
    changeHeaderMode(MODE_DEFAULT)
  }

  function changeMode(nextMode: Mode) {
    if (searchVisible.value) {
      // 如果搜索框正被打开，先将这个状态存起来
      restoreNextMode(nextMode)
      return
    }
    changeHeaderMode(nextMode)
  }

  onMounted(() => {
    if (initialMode)
      changeHeaderMode(initialMode)
  })

  const style = computed(() => {
    if (headerMode.value === 'transparent') {
      return {
        background: 'transparent',
        color: '#fff',
      }
    }
    if (headerMode.value === 'light') {
      return {
        background: '#fff',
        color: '#1f1f1f',
      }
    }
    return {}
  })

  function toggleSearch() {
    if (!pendingHeaderMode.value)
      restoreNextMode(headerMode.value)

    if (!searchVisible.value) { changeHeaderMode('light') } // 打开搜索框的时候将 header 设为 light 模式
    else {
      changeHeaderMode(pendingHeaderMode.value as Mode) // 关闭搜索框的时候恢复原来的模式
      restoreNextMode(undefined)
    }

    toggleSearchVisible()
  }

  return {
    mode: headerMode,
    searchVisible,
    style,
    changeMode,
    changeSearch: changeSearchVisible,
    toggleSearch,
  }
}
